package ec.atreasure.com.ec.launcher;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;

import java.text.MessageFormat;
import java.util.Timer;

import ec.atreasure.com.core.fragments.AtreasureFragment;
import ec.atreasure.com.core.utils.timer.BaseTimerTask;
import ec.atreasure.com.core.utils.timer.ITimerListener;
import ec.atreasure.com.ec.R;
import ec.atreasure.com.ec.login.LoginFragment;
import ec.atreasure.com.ui.launcher.ILauncherListener;

/**
 * Description :启动页界面（不带滚动页）
 * Created by wangjin on 2019/6/25.
 * Job number：
 * Phone ：18301070822
 * Email： 120182051@qq.com
 * Person in charge : 汪渝栋
 * Leader：
 */
public class LauncherFragment extends AtreasureFragment implements ITimerListener {

    //定时器
    private Timer mTimer = null;

    //显示倒计时文本
    private AppCompatTextView timerTextView;

    //倒计时初始时间
    private int mCount = 5;

    private ILauncherListener mLauncherListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (activity instanceof ILauncherListener) {
            this.mLauncherListener = (ILauncherListener) activity;
        }

    }

    @Override
    public Object setLayout() {
        return R.layout.launcher_fragment;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        timerTextView = findViewById(R.id.tv_launcher_timer);
        timerTextView.setOnClickListener(v -> onClickTimerView());
        initTimer();
    }

    private void onClickTimerView() {
        closeTimer();
        toLoginFragment();
    }

    private void initTimer() {
        mTimer = new Timer();
        final BaseTimerTask task = new BaseTimerTask(this);
        mTimer.schedule(task, 0, 1000);
    }

    @Override
    public void onTimer() {
        getAtreasureActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (timerTextView != null) {
                    timerTextView.setText(MessageFormat.format("跳过{0}s", mCount));
                    mCount--;
                    if (mCount < 1) {
                        closeTimer();
                        toLoginFragment();
                    }
                }
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        closeTimer();
    }

    @Override
    public boolean onBackPressedSupport() {
        return true;
    }

    private void closeTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    private void toLoginFragment(){
        startWithPop(new LoginFragment());
    }
}
